/*
 * @Description: 导出弹窗
 * @Author: Rfan
 * @Date: 2022-06-21 21:37:30
 * @LastEditTime: 2023-03-03 10:44:51
 */

import { useEffect, useState } from 'react';
import { Button, Form, Input, message, Modal, Select, Space, Typography } from 'antd';
import classNames from 'classnames/bind';
import { fetchMetadata } from '@/api/metadata';
import { createExportItem } from '@/api/archives/export';
import { jsonClone } from '@/utils';
import { QUERY_METADATA_ALL } from '@/view/system/Metadata/constants';
import TransferTemplate from '@/components/TransferTemplate';
import { EnumExportBusType, EnumReceiveTypes, receiveTypeName } from '@/dictionary/transfer';
import { EnumTemplateTypes } from '@/view/system/TemplateManage/dictionaries';
import type { ICreateExportParams } from '@/api/archives/export';
import type { ICommonDialog } from '@/interfaces/global';
import type { IBaseProp } from '../../index';
import type { IMetadata } from '@/interfaces/metadata';
import styles from '../../styles/exportRecordDialog.module.scss';

const cx = classNames.bind(styles);

const { Option } = Select;
interface ExportRecordDialogProps extends ICommonDialog {
  info: IBaseProp;
  selectItems: number[];
  type: EnumReceiveTypes.Excel | EnumReceiveTypes.ZIP;
}

const ExportRecordDialog = (props: ExportRecordDialogProps) => {
  const { visible, info, type, selectItems, onClose } = props;
  const [form] = Form.useForm();

  // 元数据列表
  const [metadataList, setMetadataList] = useState<IMetadata[]>([]);

  useEffect(() => {
    if (visible) {
      // 请求当前层级元数据列表
      const fieldQuery = {
        metadataFieldType: QUERY_METADATA_ALL,
        coordinate: {
          atType: info.atType,
          atCode: info.atCode,
          level: info.level
        }
      };
      fetchMetadata(fieldQuery).then((res: any) => {
        const { data } = res;
        setMetadataList(data);
      });
    }
  }, [visible]);

  /**
   * @description: 关闭弹窗
   */
  const onCancel = () => {
    form.resetFields();
    onClose();
  };

  /**
   * @description: 保存表单方法
   */
  const onFinish = (vals: any) => {
    const params: ICreateExportParams = jsonClone(vals);
    params.exportType = type;
    params.fondsId = info.fondId;
    params.archiveTypeId = info.archiveTypeId;
    params.businessType = EnumExportBusType.Export;
    params.name = `${info.levelName}-条目与原文导出`;
    params.exportEntryInfo = {
      atCode: info.atCode,
      atType: info.atType,
      level: info.level,
      entryIdList: selectItems,
      searchCondition: '',
      dbName: info.dbName
    };
    // 这里写死为1
    params.exportOriginalRule.level = 1;
    createExportItem(params).then(() => {
      message.success('导出任务创建成功');
      onCancel();
    });
  };

  return (
    <Modal
      title={`${info.levelName}-${receiveTypeName(type)}导出`}
      visible={visible}
      className={cx('export-record-dialog')}
      width={600}
      maskClosable={false}
      destroyOnClose
      onCancel={onCancel}
      footer={[
        <Button key="close" onClick={onCancel}>
          关闭
        </Button>,
        <Button
          key="export"
          type="primary"
          onClick={() => {
            form.submit();
          }}
        >
          导出
        </Button>
      ]}
    >
      <Typography.Paragraph>
        档案类型：
        {info.atName}
      </Typography.Paragraph>
      <Typography.Title level={5}>
        已选择条目：{selectItems.length === 0 ? '全部' : selectItems.length}
      </Typography.Title>
      <Form
        form={form}
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 16 }}
        preserve={false}
        onFinish={onFinish}
      >
        <Form.Item
          name="templateId"
          label="模板配置"
          extra="请选择档案导出条件模板，规则模板可在“模板设计”内配置)"
          rules={[{ required: true, message: '请选择模板' }]}
        >
          <TransferTemplate tplType={EnumTemplateTypes.ExcelExport} />
        </Form.Item>
        <Form.Item
          label="电子原文导出配置"
          extra="根据配置解析字段（一般为文件档号）层次，并在系统执行导出时生成文件夹层级，相关电子文件放置在最后一个文件夹内。"
        >
          <Space>
            <Form.Item
              name={['exportOriginalRule', 'fieldName']}
              rules={[{ required: true, message: '请选择字段' }]}
              noStyle
            >
              <Select style={{ width: 140 }}>
                {metadataList.map((metadata: IMetadata) => (
                  <Option key={metadata.id} value={metadata.field_name}>
                    {metadata.field_desc}
                  </Option>
                ))}
              </Select>
            </Form.Item>
            <Form.Item noStyle>匹配分割符</Form.Item>
            <Form.Item
              name={['exportOriginalRule', 'concatMark']}
              rules={[{ required: true, message: '请输入分隔符' }]}
              noStyle
            >
              <Input style={{ width: 60 }} />
            </Form.Item>
          </Space>
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default ExportRecordDialog;
